package com.cloud.salon.gateway.component.handler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloud.salon.gateway.bean.UserDetailImpl;
import com.cloud.salon.gateway.util.TokenAuthenticationUtil;
import com.cloud.salon.common.base.response.Res;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
        
        UserDetails userinfo = (UserDetails) authentication.getPrincipal();

        String jwtToken = TokenAuthenticationUtil.generateToken(userinfo);

        // 设置返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("jwtToken", jwtToken);
        map.put("authority", userinfo.getAuthorities());
        map.put("staff", ((UserDetailImpl) userinfo).getStaff());


        Res<Map<String, String>> res = new Res(0, "登陆成功!", map);

        response.getWriter().write(JSON.toJSONString(res));
	}
}
